package controller;

import model.MySql;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 修改用户密码
 * Created by yvdedu.com on 2016/9/27.
 */
@WebServlet(urlPatterns = "/update_userpwd")
public class update_userpwd extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String name=req.getParameter("name");
        String old_pwd=req.getParameter("old_pwd");
        String new_pwd=req.getParameter("new_pwd");
        String sec_pwd=req.getParameter("sec_pwd");
        if(name!=null&&old_pwd!=null&&new_pwd!=null&&sec_pwd!=null){
            MySql mySql=new MySql();
            model.User user=mySql.getUserByName(name);
            if(user==null){
                resp.getWriter().print("用户名不存在，请重试！");
                System.out.println("用户不存在");
            }else{
                if(!old_pwd.equals(user.getPwd())){
                    resp.getWriter().print("原密码错误，请重试！");
                    System.out.println("原密码错误");
                }else if(!new_pwd.equals(sec_pwd)){
                    resp.getWriter().print("两次密码不一致，请重试！");
                    System.out.println("密码不一致");
                }else{
                    Boolean result=mySql.setUserPwd(name,new_pwd);
                    if (result){
                        req.getSession().setAttribute("user",mySql.getUserByName(name));
                        resp.getWriter().print("恭喜您，修改成功！");
                        System.out.println("密码修改成功");
                    }else{
                        resp.getWriter().print("对不起，密码修改失败，请重试！");
                        System.out.println("修改失败");
                    }
                }
            }
        }else{
            resp.getWriter().print("用户名或密码不能为空！");
            System.out.println("用户名或密码不能为空");
        }
    }
}
